package com.hoffm59.facebookcontactsync.util;

import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.content.ContentProviderOperation;
import android.content.ContentResolver;
import android.content.OperationApplicationException;
import android.database.Cursor;
import android.os.RemoteException;
import android.provider.ContactsContract;
import android.support.v4.content.CursorLoader;

import com.facebook.model.GraphUser;

/**
 * @author HOFFM59
 */
public class ContactHelper {

    public static void syncContacts(final Activity context, List<GraphUser> selectedUsers) {

        for (final GraphUser user : selectedUsers) {

            addContact(context, user);
// Toast.makeText(context, user.getProperty("name").toString(), Toast.LENGTH_SHORT).show();
        }
    }

    private static void addContact(final Activity context, final GraphUser user) {

        final ContentResolver cr = context.getContentResolver();

        final String userName = user.getProperty("name").toString();
        final String userLink = user.getProperty("link").toString();

        final Cursor cur = cr.query(ContactsContract.Contacts.CONTENT_URI, null, null, null, null);

        if (cur.getCount() > 0) {
            while (cur.moveToNext()) {
                final String existName = cur.getString(cur.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
                if ((existName != null) && existName.contains(userName)) {

                    updateContact(context, user);
                }
            }
        }

        final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();
        ops.add(ContentProviderOperation.newInsert(ContactsContract.RawContacts.CONTENT_URI)
                .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
                .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null).build());

        // Add contact name
        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE,
                        ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME, userName).build());

        // Add contact link
        ops.add(ContentProviderOperation
                .newInsert(ContactsContract.Data.CONTENT_URI)
                .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
                .withValue(ContactsContract.Data.MIMETYPE, ContactsContract.CommonDataKinds.Website.CONTENT_ITEM_TYPE)
                .withValue(ContactsContract.CommonDataKinds.Website.URL, userLink)
                .withValue(ContactsContract.CommonDataKinds.Website.TYPE,
                        ContactsContract.CommonDataKinds.Website.TYPE_PROFILE).build());

        try {
            context.getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (final Exception e) {
            e.printStackTrace();
        }
    }

    private static void updateContact(final Activity context, final GraphUser user) {

        final ContentResolver cr = context.getContentResolver();

        final String where = ContactsContract.Data.DISPLAY_NAME + " = ? ";
        final String[] params = new String[] { user.getProperty("name").toString() };

        final Cursor phoneCur =
                new CursorLoader(context, ContactsContract.Data.CONTENT_URI, null, where, params, null)
                        .loadInBackground();

        final ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

        if ((null == phoneCur)) {
            addContact(context, user);
        } else {
            // TODO Update contact
// ops.add(ContentProviderOperation.newUpdate(ContactsContract.Data.CONTENT_URI).withSelection(where, params)
// .withValue(ContactsContract.CommonDataKinds.Phone.DATA, phone).build());
        }

        phoneCur.close();

        try {
            cr.applyBatch(ContactsContract.AUTHORITY, ops);
        } catch (final RemoteException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (final OperationApplicationException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // TODO HOW-TO
// String DisplayName = "XYZ";
// String MobileNumber = "123456";
// String HomeNumber = "1111";
// String WorkNumber = "2222";
// String emailID = "email@nomail.com";
// String company = "bad";
// String jobTitle = "abcd";
//
// ArrayList < ContentProviderOperation > ops = new ArrayList < ContentProviderOperation > ();
//
// ops.add(ContentProviderOperation.newInsert(
// ContactsContract.RawContacts.CONTENT_URI)
// .withValue(ContactsContract.RawContacts.ACCOUNT_TYPE, null)
// .withValue(ContactsContract.RawContacts.ACCOUNT_NAME, null)
// .build());
//
// //------------------------------------------------------ Names
// if (DisplayName != null) {
// ops.add(ContentProviderOperation.newInsert(
// ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.StructuredName.CONTENT_ITEM_TYPE)
// .withValue(
// ContactsContract.CommonDataKinds.StructuredName.DISPLAY_NAME,
// DisplayName).build());
// }
//
// //------------------------------------------------------ Mobile Number
// if (MobileNumber != null) {
// ops.add(ContentProviderOperation.
// newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, MobileNumber)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
// ContactsContract.CommonDataKinds.Phone.TYPE_MOBILE)
// .build());
// }
//
// //------------------------------------------------------ Home Numbers
// if (HomeNumber != null) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, HomeNumber)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
// ContactsContract.CommonDataKinds.Phone.TYPE_HOME)
// .build());
// }
//
// //------------------------------------------------------ Work Numbers
// if (WorkNumber != null) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Phone.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Phone.NUMBER, WorkNumber)
// .withValue(ContactsContract.CommonDataKinds.Phone.TYPE,
// ContactsContract.CommonDataKinds.Phone.TYPE_WORK)
// .build());
// }
//
// //------------------------------------------------------ Email
// if (emailID != null) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Email.DATA, emailID)
// .withValue(ContactsContract.CommonDataKinds.Email.TYPE, ContactsContract.CommonDataKinds.Email.TYPE_WORK)
// .build());
// }
//
// //------------------------------------------------------ Organization
// if (!company.equals("") && !jobTitle.equals("")) {
// ops.add(ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
// .withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
// .withValue(ContactsContract.Data.MIMETYPE,
// ContactsContract.CommonDataKinds.Organization.CONTENT_ITEM_TYPE)
// .withValue(ContactsContract.CommonDataKinds.Organization.COMPANY, company)
// .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
// ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
// .withValue(ContactsContract.CommonDataKinds.Organization.TITLE, jobTitle)
// .withValue(ContactsContract.CommonDataKinds.Organization.TYPE,
// ContactsContract.CommonDataKinds.Organization.TYPE_WORK)
// .build());
// }
//
// // Asking the Contact provider to create a new contact
// try {
// getContentResolver().applyBatch(ContactsContract.AUTHORITY, ops);
// } catch (Exception e) {
// e.printStackTrace();
// Toast.makeText(myContext, "Exception: " + e.getMessage(), Toast.LENGTH_SHORT).show();
// }
}